﻿using AutoMapper;
using BaseData.Domain;
using BaseData.ErrorCode;
using BaseData.Infrastructure.DTO;
using BaseData.Infrastructure.Interfaces;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static BaseData.Domain.Approvals;

namespace BaseData.Infrastructure.Approval
{
    public class ApprovalService : IApprovalService
    {
        private readonly IBaseRepository<Approvals> appRep;
        private readonly IMapper mapper;
        private readonly IBaseRepository<Users> userRep;

        public ApprovalService(IBaseRepository<Approvals> appRep,IMapper mapper,IBaseRepository<Users> userRep)
        {
            this.appRep = appRep;
            this.mapper = mapper;
            this.userRep = userRep;
        }
        public async Task<APIResult<int>> ApprovalMetting(int id, int state, string? remark)
        {
            var result = await appRep.GetAll().FirstOrDefaultAsync(x=>x.ApprovalsId==id);
            if (result != null)
            {
                result.Result =(ApprovalResult)state;
                result.Status  = ApprovalState.已审批;
                result.ApprovalRemark = remark;
                await  appRep.UpdateAsync(result);
                return new APIResult<int>
                {
                    Code = CodeEnum.Success,
                    Message="审批成功",
                    Data =1
                };
            }
            return new APIResult<int>
            {
                Code = CodeEnum.Failed,
                Message = "审批失败",
                Data = 0
            };
        }

        public async Task<List<ApprovalDTO>> ShowApprove(int state, string? subject, string? mettingroom)
        {
            try
            {
                var list = await appRep.GetAll().Where(x=>x.Status== (ApprovalState)state).ToListAsync();
                if(!string.IsNullOrEmpty(subject))
                {
                    list = list.Where(x=>x.Subject.Contains(subject)).ToList();
                }
                if(!string.IsNullOrEmpty(mettingroom))
                {
                    list = list.Where(x=>x.MeetRoomName.Contains(mettingroom)).ToList();
                }
                var dto = mapper.Map<List<ApprovalDTO>>(list);
                foreach (var item in dto)
                {
                    item.UserName = (userRep.GetAll().FirstOrDefault(x => x.UsersId == item.UserId)?.UserName);
                    
                }
                return dto;
            }
            catch (Exception)
            {

                throw;
            }
        }
    }
}
